iT邦幫忙

2021 iThome 鐵人賽

DAY 29
1
自我挑戰組

C# 學習之旅系列 第 29

ASP.NET MVC 從入門到放棄(Day29)-MVC 實作一個web api

  • 分享至 

  • xImage
  •  

在前一天我有提到如何將Web Api 加入 Swagger
今天就來實作一個會員查詢資料的POST 方法的 Web Api

1.預想Json格式呼叫(傳入)的方法為

  {
     "MemberId": "1111",	
     "MemberName": "11111",
   }

2.建立會員Model模板

public class Member
{
   /// <summary>
   /// 會員編號
   /// </summary>
   [Display(Name = "會員編號")]
   [StringLength(10, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 0)]
   public string MemberId { get; set; }


    /// <summary>
    /// 會員姓名
    /// </summary>
    [Display(Name = "會員姓名")]
    [StringLength(10, ErrorMessage = "{0}的長度至少必須為{2}的字元。", MinimumLength = 0)]
    public string MemberName { get; set; }

}

3.預想Json格式呼叫(傳出)的方法為

{
    "code": "S001",
    "message": "查詢成功",
    "stauts": "成功",
    "data": [
        {
            "memberId": "1111",
            "memberName": "Yaowen"
        }
    ]
}

4.建立傳出Model模板

public class Result2<T>
{
   public string Code { get; set; }
   public string Message { get; set; }
   public string Stauts { get; set; }
   public List<T> Data { get; set; } = new List<T>();
}

5.Controller 開始寫邏輯

 #region 查詢會員資料
/// <summary>
/// 查詢會員資料
/// </summary>
/// <response code="S001">查詢成功</response>
/// <response code="E001">查無資料</response>
/// <response code="E002">不在效期內</response>
/// <response code="E003">未知錯誤</response>
///  <remarks>
///   {
///        "MemberId": "1111",	
///        "MemberName": "11111",
///     }
///  </remarks>
[HttpPost("GetMember")]
public Result2<MemberData> GetMember([FromBody] Member member)
{

            

   var Config = new Config();
   Config.connectionString = _config.GetValue<string>("connectionString");


   Result2<MemberData> result = new Result2<MemberData>();




   if (String.IsNullOrEmpty(member.MemberId) && String.IsNullOrEmpty(member.MemberName))
   {
        result.Code = "E001";
        result.Message = "查無資料";
        result.Stauts = "失敗";
        return result;
    }

    try
    {
       using (var conn = new MySqlConnection(Config.connectionString))
       {

          conn.Open();

          using (var command = conn.CreateCommand())
          {
              command.CommandText = "SELECT MemberId,MemberName FROM Member WHERE 1 = 1 ";
              if (!String.IsNullOrEmpty(member.MemberId))
              {
                 command.CommandText += " And memberid like @MmeberId ";
                 command.Parameters.AddWithValue("@MmeberId", "%" + member.MemberId);
              }

              if (!String.IsNullOrEmpty(member.MemberName))
              {
                 command.CommandText += " And MemberName like @MemberName ";
                 command.Parameters.AddWithValue("@MemberName", "%" + member.MemberName);
              }


             using (var reader = command.ExecuteReader())
             {
                if (reader.HasRows)
                {
                   result.Code = "S001";
                   result.Message = "查詢成功";
                   result.Stauts = "成功";

                   while (reader.Read())
                   {
             
                       result.Data.Add(new MemberData() { 
                                    
                      MemberId = (reader.IsDBNull(reader.GetOrdinal("MemberId"))) ? "" : (string)reader["MemberId"],
                      MemberName = (reader.IsDBNull(reader.GetOrdinal("MemberName"))) ? "" : (string)reader["MemberName"]
                      });
   
                    }

                              


                  return result;
               }
               else
               {
                  result.Code = "E001";
                  result.Message = "查無資料";
                  result.Stauts = "失敗";
                 return result;
                 }
         }
      }


}
            }
            catch (Exception ex)
            {
                result.Code = "E003";
                result.Message = ex.Message;
                result.Stauts = "未知錯誤";
                return result;
            }
        }

        #endregion

註解:Controller 可以另外拆開把邏輯的部分放在Model底下(正常資料庫存取部分是要放在Model底下),但這邊快速講解流程故邏輯先寫在Controller底下

6.使用PostMan進行測試
https://ithelp.ithome.com.tw/upload/images/20210908/20140001zRvaBnaxiY.png

7.或者可以使用Swagger進行測試
https://ithelp.ithome.com.tw/upload/images/20210908/20140001pTscL9QvVI.png


上一篇
ASP.NET MVC 從入門到放棄(Day28)- MVC web api 加入swagger介紹
下一篇
ASP.NET MVC 從入門到放棄(Day30)-總結
系列文
C# 學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言